# coding: utf-8
from typing import List

from PySide6.QtCore import Qt, QSize
from PySide6.QtWidgets import QVBoxLayout, QListWidgetItem
from qfluentwidgets import themeColor

from components import TagListWidget, GridLayout, Alert
from server.api import MianKouTuAPI
from ..base import BaseInterface, WallpaperCard


class MktpInterface(BaseInterface):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.tempData = {
            'currentPage': 0,
            'isLastPage': False,
            'configKey': '',
            'tag': '',
            'sortType': 0,
        }

        self.verticalLayout = QVBoxLayout(self.view)
        self.firstListWidget = TagListWidget(self.view)
        self.secondListWidget = TagListWidget(self.view)
        self.threeListWidget = TagListWidget(self.view)
        self.sortListWidget = TagListWidget(self.view)
        self.waterfallLayout = GridLayout()

        self.__initWidgets()
        self.__initLayout()

        self.connectSignals()

    def __initWidgets(self):
        self.setObjectName("MktpInterface")
        self.waterfallLayout.setItemMinimumWidth(150)
        self.waterfallLayout.setContentsMargins(0, 0, 0, 0)

        self.secondListWidget.setVisible(False)
        self.threeListWidget.setVisible(False)

        self.firstListWidget.setTag('一级分类：')
        self.secondListWidget.setTag('二级分类：')
        self.threeListWidget.setTag('三级分类：')
        self.sortListWidget.setTag('排序：')

        item = QListWidgetItem('今日灵感')
        item.setData(Qt.ItemDataRole.UserRole, '今日灵感')
        self.firstListWidget.addItem(item)
        self.firstListWidget.setCurrentRow(0)

        sortList = [('热门', 0), ('最新', 1), ('最热', 2), ('发现', 3)]
        for text, key in sortList:
            item = QListWidgetItem(text)
            item.setData(Qt.ItemDataRole.UserRole, key)
            self.sortListWidget.addItem(item)
        self.sortListWidget.setCurrentRow(0)

    def __initLayout(self):
        self.verticalLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.addWidget(self.firstListWidget, 0, Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.addWidget(self.secondListWidget, 0, Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.addWidget(self.threeListWidget, 0, Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.addWidget(self.sortListWidget, 0, Qt.AlignmentFlag.AlignTop)
        self.verticalLayout.addLayout(self.waterfallLayout)

    def connectSignals(self):
        self.firstListWidget.itemClicked.connect(self.onFirstTagChanged)
        self.secondListWidget.itemClicked.connect(self.onSecondTagChanged)
        self.threeListWidget.itemClicked.connect(self.onThreeTagChanged)
        self.sortListWidget.itemClicked.connect(self.onSortTagChanged)

        self.load(MianKouTuAPI.queryConfig, slot=self.onFirstQueryConfig)
        self.loadQuery()

    def addLabel(self, url: str, title: str, max_url: str):
        label = super().addLabel(url, self.waterfallLayout, QSize(150, 150))
        color = themeColor()
        color.setAlpha(100)
        label.setBackground(color)
        label.setMaxUrl(max_url)
        return label

    def clear(self):
        self.tempData.update({'currentPage': 0, 'isLastPage': False})
        self.waterfallLayout.takeAllWidgets()

    def nextPage(self):
        if self.tempData['isLastPage']:
            return
        self.tempData['currentPage'] += 1
        self.loadQuery()

    def loadQuery(self):
        tag = self.firstListWidget.currentItem().data(Qt.ItemDataRole.UserRole)
        if tag == '今日灵感':
            self.commonList()
        else:
            self.queryByTag()

    def onLabelFinished(self, label: WallpaperCard):
        if label.isNull():
            return
        image = label.image
        image = image.scaledToWidth(150, Qt.TransformationMode.SmoothTransformation)
        label.setMinimumSize(image.size())

    def onFirstQueryConfig(self, result: List[dict]):
        for data in result:
            item = QListWidgetItem(data['name'])
            item.setData(Qt.ItemDataRole.UserRole, data['tag'])
            item.setData(Qt.ItemDataRole.UserRole + 1, data['configKey'])
            self.firstListWidget.addItem(item)

    def onFirstTagChanged(self, item: QListWidgetItem):
        tag = item.data(Qt.ItemDataRole.UserRole)
        configKey = item.data(Qt.ItemDataRole.UserRole + 1)
        if tag == '今日灵感':
            self.secondListWidget.setVisible(False)
            self.threeListWidget.setVisible(False)
            self.clear()
            self.commonList()
            return
        self.secondListWidget.setVisible(True)
        self.load(MianKouTuAPI.queryConfig, configKey, slot=self.onSecondQueryConfig)
        self.tempData.update({'configKey': configKey, 'tag': tag, 'currentPage': 0, 'isLastPage': False})
        self.clear()
        self.queryByTag()

    def onSecondTagChanged(self, item: QListWidgetItem):
        children = item.data(Qt.ItemDataRole.UserRole + 1)
        if children:
            self.threeListWidget.clear()
            self.threeListWidget.setVisible(True)
            for child in children:
                childItem = QListWidgetItem(child['name'])
                childItem.setData(Qt.ItemDataRole.UserRole, child['tag'])
                self.threeListWidget.addItem(childItem)
            self.threeListWidget.setCurrentRow(0)
        else:
            self.threeListWidget.setVisible(False)

        tag = item.data(Qt.ItemDataRole.UserRole)
        if not tag:
            tag = self.threeListWidget.currentItem().data(Qt.ItemDataRole.UserRole)
        self.tempData['tag'] = tag
        self.clear()
        self.loadQuery()

    def onSecondQueryConfig(self, result: dict):
        self.secondListWidget.clear()
        for data in result:
            item = QListWidgetItem(data['name'])
            item.setData(Qt.ItemDataRole.UserRole, data.get('tag', ''))
            item.setData(Qt.ItemDataRole.UserRole + 1, data.get('children', []))
            self.secondListWidget.addItem(item)
        self.secondListWidget.setCurrentRow(0)

    def onThreeTagChanged(self, item: QListWidgetItem):
        tag = item.data(Qt.ItemDataRole.UserRole)
        if not tag:
            return
        self.tempData['tag'] = tag
        self.clear()
        self.loadQuery()

    def onSortTagChanged(self, item: QListWidgetItem):
        self.tempData['sortType'] = item.data(Qt.ItemDataRole.UserRole)
        self.clear()
        self.loadQuery()

    def queryByTag(self):
        tag = self.tempData['tag']
        sortType = self.tempData['sortType']
        currentPage = self.tempData['currentPage']
        self.load(MianKouTuAPI.queryByTag, tag, sortType, currentPage, slot=self.onQueryResultToDisplay)

    def commonList(self):
        page = self.tempData['currentPage']
        sort_type = self.tempData['sortType']
        self.load(MianKouTuAPI.commonList, page, sort_type, slot=self.onQueryResultToDisplay)

    def onQueryResultToDisplay(self, result: dict):
        if result['code'] == 200:
            dataList = result['data']
            if not dataList:
                Alert.warning('没有更多数据了')
                self.tempData['isLastPage'] = True
                return
            for data in dataList:
                self.addLabel(data['thumbUrl'], data['detailInfo'], data['largeUrl'])
        else:
            Alert.error(result['error_msg'])
        self.lazyTimerStart()

    def onReload(self):
        self.clear()
        self.loadQuery()
